package fpt.edu.vn.action;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fpt.edu.vn.dao.UsersDao;

public class UpdateProfileAction extends ActionSupport implements
		ServletRequestAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File userImage;
	private String userImageContentType;
	private String userImageFileName;
	private String username;

	UsersDao userdao = new UsersDao();

	Map<String, Object> session;

	private int userId;

	private HttpServletRequest servletRequest;

	public String execute() {
		int userId_ = 0;
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userIdss")) {
			userId_ = (Integer) session.get("userIdss");
			setUserId(userId_);
		}
		try {

			if (userImage != null) {
				String filePath = servletRequest.getRealPath("/");
				File fileToCreate = new File(filePath, this.userImageFileName);
				FileUtils.copyFile(this.userImage, fileToCreate);
				userdao.UpdateProfile(userId, username, userImageFileName);
			} else {
				userdao.UpdateProfile(userId, username);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			addActionError("Ảnh đại diện phải dưới 2mb");
			return INPUT;
		}
		session = ActionContext.getContext().getSession();
		session.put("displayNamess", username);
		return SUCCESS;
	}

	public File getUserImage() {
		return userImage;
	}

	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}

	public String getUserImageContentType() {
		return userImageContentType;
	}

	public void setUserImageContentType(String userImageContentType) {
		this.userImageContentType = userImageContentType;
	}

	public String getUserImageFileName() {
		return userImageFileName;
	}

	public void setUserImageFileName(String userImageFileName) {
		this.userImageFileName = userImageFileName;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;

	}

	public String getUsername() {
		return username;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}
